var express = require("express");
var router = express.Router();
//引入自定义的controller
const UserController = require("../controllers/user");

var $mysql = require("mysql");
var sql = require("../mysql/mysql"); //这句话是，引入当前目录的mysql模板   mysql就是我们上面创建的mysql.js
// 解析,用req.body获取post参数
var bodyParser = require("body-parser");

var jsonParser = bodyParser.json(); // for parsing application/json
var urlencodedParser = bodyParser.urlencoded({ extended: true }); // for parsing application/x-www-form-urlencoded
const Token = require("../utils/token");

/* GET users listing. */
router.post("/loginRegister", jsonParser, function (req, res, next) {
  let phone = req.body.phoneNo;
  let password = req.body.password;
  var $sql = $mysql.createConnection(sql.mysql); //创建一个连接        mysql是我们上面文件暴露出来的模板的方法
  $sql.connect();
  /** 1.首先判断数据库中是否有此用户 */
  // 使用 Promise 的原因是因为中间调用了两次数据库，而数据库查询是异步的，所以需要用 Promise。
  new Promise((resolve, reject) => {
    // 查询的 SQL 语句及查询的字段信息
    let readSql = `SELECT * FROM user WHERE phone=${phone};`;
    $sql.query(readSql, function (err, rows, fields) {
      if (err) throw err;
      console.log("The solution is: ", rows);
      if (rows[0]) {
        /** 有此用户，进行登录 */

        resolve("login");
      } else {
        /** 无此用户，进行注册 */
        resolve("register");
      }
    });
  }).then((handleType) => {
    if (handleType === "login") {
      let token = Token.encrypt({ phone, password });
      // let token = generateToken(phone, password);
      /** 登录 */
      // 查询的 SQL 语句及查询的字段信息
      let readSql = "SELECT * FROM user WHERE phone=?;";
      let readSqlParams = [phone];
      $sql.query(readSql, readSqlParams, function (err2, rows2, fields2) {
        if (err2) throw err2;
        console.log(rows2);
        let { phone, nick_name, theme, email } = rows2[0];
        res.send({
          isOk: true,
          code: 200,
          result: {
            phoneNo: phone,
            nickname: nick_name,
            theme: theme,
            email: email,
            token,
          },
          message: "register success",
        });
      });
    } else {
      /** 注册 */
      // 新增的 SQL 语句及新增的字段信息
      let addSql = "INSERT INTO user (phone,password) VALUES(?,?)";
      let addSqlParams = [phone, password];

      $sql.query(addSql, addSqlParams, function (err2, rows2, fields2) {
        if (err2) throw err2;
        console.log("The solution is: ", rows2);

        let token = Token.encrypt({ phone, password }).token;
        res.send({
          isOk: true,
          code: 200,
          result: {
            phoneNo: phone,
            token,
          },
          message: "register success",
        });
      });
    }
    $sql.end();
  });
  //Promise结束
});

router.post("/loginStatus", jsonParser, function (req, res, next) {
  //1.获取客户端传递来的token
  let token = req.body.token;
  console.log("token", token);
  //2.校验token
  let tokenVerifyResult = Token.decrypt(token);
  if (tokenVerifyResult.token) {
    let phone = tokenVerifyResult.data.phone;
    //校验成功

    var $sql = $mysql.createConnection(sql.mysql); //创建一个连接        mysql是我们上面文件暴露出来的模板的方法
    $sql.connect();
    // 查询的 SQL 语句及查询的字段信息
    let readSql = "SELECT * FROM user WHERE phone=?;";
    let readSqlParams = [phone];
    $sql.query(readSql, readSqlParams, function (err2, rows2, fields2) {
      if (err2) throw err2;
      console.log(rows2[0]);
      $sql.end();
      //数据返回给前端
      let { phone, nick_name, theme, email, password } = rows2[0];
      let newToken = Token.encrypt({ phone, password });
      res.send({
        isOk: true,
        code: 200,
        result: {
          phoneNo: phone,
          nickname: nick_name,
          theme: theme,
          email: email,
          token: newToken,
        },
        message: "auto login success",
      });
    });
  } else {
    //一旦报错了，说明用户信息校验失败
    res.send({
      isOk: true,
      code: 413,
      result: null,
      message: "login failed,token expired",
    });
  }
});

/** 修改用户信息 */
router.post("/modifyUserInfo", jsonParser, UserController.modifyUserInfo);

/** 退出登录 */
router.post("/logOut",jsonParser,UserController.logOut);

module.exports = router;
